import { useRequest } from 'ahooks'
import React, { FC, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { changeuserinfoAPI, uplodafileAPI } from '../api/api'
import { changeUserInfo } from '../rtk/reducers/info'





const UploadFile: FC<any> = ({
  children
}) => {
  const fileRef: any = useRef()
  const dispatch = useDispatch()
  const { userInfo } = useSelector((state: any) => state.info)

  // 接口上传文件
  const uploadFileData = useRequest(uplodafileAPI, {
    manual: true,
    onSuccess: (res: any, params: any) => {
      if (res.code == 200) {
        // 先改服务器端的头像信息
        changeuserinfoData.run({
          avatar: res.path
        })
      }
    }
  })

  const changeuserinfoData = useRequest(changeuserinfoAPI, {
    manual: true,
    onSuccess: (res: any, params: any) => {
      if (res.code == 200) {
        // 先改前端的头像信息
        dispatch(changeUserInfo({
          ...userInfo,
          ...params[0]
        }))
      }
    }
  })


  const onUploadFiles = () => {
    const file = fileRef.current.files[0]
    const data = new FormData() // 新建表单对象
    data.append('file', file)
    uploadFileData.run(data)
  }

  const startUpload = () => {
    fileRef.current.click()
  }

  return (
    <div onClick={startUpload}>
      <input onChange={onUploadFiles} type='file' style={{ display: 'none' }} ref={fileRef} />
      {children}
    </div>
  )
}

export default UploadFile
